/*
 *
 *  Copyright (C) 2010 Tal Eisenberg
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package tal.drivechain.module.properties;

import java.util.HashMap;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import tal.drivechain.chain.ChainNode;
import tal.drivechain.parsing.Tokenizer;

/**
 *
 * @author Main
 */
public class ComplexParser implements PropertyParser {
    HashMap<Integer, PropertyParser> parsers = new HashMap<Integer, PropertyParser>();
    char delim = ',';
    
    public String getDescription() {
        String ret = "complex-parser (";
        for (int i=0; i<parsers.size(); i++) {
            PropertyParser p = parsers.get(i);
            if (p!=null)
                ret += p.getPropertyType() + delim;
        }
        return ret.substring(0, ret.length()-1) + ")";
    }
    
    public String getPropertyType() {
        String ret = "";
        for (int i=0; i<parsers.size(); i++) {
            PropertyParser p = parsers.get(i);
            if (p!=null)
                ret += p.getPropertyType() + delim;
        }
        return ret.substring(0, ret.length()-1);
    }

    public void setAttribures(HashMap<String, String> attributes, NodeList childElements) throws IllegalArgumentException {
        //<complex-parser delimiter=",">
        //  <0.var-parser....
        for (int i=0; i<childElements.getLength(); i++) {
            Node parser = childElements.item(i);
            String parserName = parser.getNodeName();
            if (!parserName.equals("#text")) {
                HashMap<String,String> parserAttributes = new HashMap<String,String>();
                NamedNodeMap attrMap = parser.getAttributes();
                for (int z=0; z<attrMap.getLength(); z++) {
                    parserAttributes.put(attrMap.item(z).getNodeName(), attrMap.item(z).getNodeValue());
                }
                try {
                    int dotIdx = parserName.lastIndexOf('.');
                    if (dotIdx==-1)
                        throw new IllegalArgumentException("parser name must end with a dot following an index number.");
                    int parserIdx = -1;
                    try {
                        parserIdx = Integer.parseInt(parserName.substring(dotIdx+1));
                    } catch (NumberFormatException ne) {
                        throw new IllegalArgumentException("Invalid parser index: " + parserName.substring(0, dotIdx));
                    }
                    PropertyParser propParser = PropertyParserFactory.createParser(parserName.substring(0,dotIdx), parserAttributes, parser.getChildNodes());
                    parsers.put(parserIdx, propParser);
                } catch (IllegalArgumentException ex) {
                    throw new IllegalArgumentException("at parser " + parserName + ", " + ex.getMessage());
                }
            }
        }
        String delimiter = attributes.get("delimiter");
        if (delimiter!=null) delim = delimiter.charAt(0);
    }

    public Object parseProperty(String prop) throws IllegalArgumentException {
        prop = prop.trim();
/*      if (prop.charAt(0)=='{' && prop.charAt(prop.length()-1)=='}')
            prop = prop.substring(1, prop.length()-1);
        else throw new IllegalArgumentException("Complex parser value must be surrounded by curly brackets ('{}')");*/

        Tokenizer tokenizer = new Tokenizer(prop, delim);
        Object[] ret = new Object[tokenizer.countTokens()];
        if (parsers.size()>tokenizer.countTokens()) {
            throw new IllegalArgumentException("Required child properties are missing. required: " + getPropertyType());
        }
        for (int i=0; i<tokenizer.countTokens(); i++) {
            PropertyParser parser = parsers.get(i);
            if (parser==null)
                throw new IllegalArgumentException("No parser assigned for delimited property no. " + i);
            else
                ret[i] = parsers.get(i).parseProperty(tokenizer.getTokens()[i]);
        }
        return ret;
    }

    public String propToString(Object property, ChainNode context) {
        Object[] value = (Object[])property;
        String ret = "";
        for (int i=0; i<value.length; i++)
            ret += parsers.get(i).propToString(value[i], context) + delim;
        return ret.substring(0, ret.length()-1) + "";
    }

}
